package com.wgh.pay.controller;

import com.wgh.pay.entity.ReconciliationDiff;
import com.wgh.pay.entity.ReconciliationResult;
import com.wgh.pay.service.ReconciliationService;
import com.wgh.pay.vo.ReconciliationReportVO;
import com.wgh.common.vo.PageResult;
import com.wgh.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

/**
 * 对账管理控制器
 */
@RestController
@RequestMapping("/api/reconciliation")
public class ReconciliationController {

    @Autowired
    private ReconciliationService reconciliationService;

    /**
     * 执行对账操作
     * @param reconciliationDate 对账日期
     * @param payType 支付方式（可选）
     * @return 对账结果
     */
    @PostMapping("/execute")
    public Result<?> executeReconciliation(
            @RequestParam("reconciliationDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date reconciliationDate,
            @RequestParam(value = "payType", required = false) Integer payType) {
        try {
            ReconciliationResult result = reconciliationService.reconcile(reconciliationDate, payType);
            return Result.success("对账任务执行成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("对账任务执行失败：" + e.getMessage());
        }
    }

    /**
     * 查询对账记录列表
     * @param params 查询参数
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return 分页结果
     */
    @GetMapping("/list")
    public Result<?> queryReconciliationRecords(
            @RequestParam Map<String, Object> params,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<ReconciliationResult> pageResult = reconciliationService.queryReconciliationRecords(params, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询对账记录失败：" + e.getMessage());
        }
    }

    /**
     * 查询对账详情
     * @param id 对账结果ID
     * @return 对账详情
     */
    @GetMapping("/detail/{id}")
    public Result<?> getReconciliationDetail(@PathVariable Long id) {
        try {
            // 此处简化实现，实际应根据ID查询详情
            Map<String, Object> result = new HashMap<>();
            // 添加查询逻辑
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询对账详情失败：" + e.getMessage());
        }
    }

    /**
     * 生成对账报表
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param payType 支付方式（可选）
     * @return 对账报表
     */
    @GetMapping("/report")
    public Result<?> generateReconciliationReport(
            @RequestParam("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(value = "payType", required = false) Integer payType) {
        try {
            ReconciliationReportVO report = reconciliationService.generateReconciliationReport(startDate, endDate, payType);
            return Result.success("对账报表生成成功", report);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("对账报表生成失败：" + e.getMessage());
        }
    }

    /**
     * 处理对账差异
     * @param orderId 订单ID
     * @param status 处理状态
     * @param remark 备注
     * @return 处理结果
     */
    @PostMapping("/handle-diff")
    public Result<?> handleReconciliationDiff(
            @RequestParam Long orderId,
            @RequestParam Integer status,
            @RequestParam(required = false) String remark) {
        try {
            boolean success = reconciliationService.handleReconciliationDiff(orderId, status, remark);
            if (success) {
                return Result.success(null, "对账差异处理成功");
            } else {
                return Result.error("对账差异处理失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("对账差异处理失败：" + e.getMessage());
        }
    }

    /**
     * 导出对账数据
     * @param reconciliationDate 对账日期
     * @param payType 支付方式（可选）
     * @return 导出文件路径
     */
    @GetMapping("/export")
    public Result<?> exportReconciliationData(
            @RequestParam("reconciliationDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date reconciliationDate,
            @RequestParam(value = "payType", required = false) Integer payType) {
        try {
            String filePath = reconciliationService.exportReconciliationData(reconciliationDate, payType);
            return Result.success("对账数据导出成功", filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("对账数据导出失败：" + e.getMessage());
        }
    }

    /**
     * 上传渠道对账文件
     * @param file 上传的文件
     * @param payType 支付方式
     * @param reconciliationDate 对账日期
     * @return 上传结果
     */
    @PostMapping("/upload-channel-file")
    public Result<?> uploadChannelReconciliationFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam Integer payType,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date reconciliationDate) {
        try {
            // 此处简化实现，实际应保存文件并解析
            String fileName = file.getOriginalFilename();
            // 保存文件到临时目录
            File tempFile = File.createTempFile("channel_reconciliation_", fileName.substring(fileName.lastIndexOf(".")));
            file.transferTo(tempFile);
            
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("filePath", tempFile.getAbsolutePath());
            result.put("fileSize", file.getSize());
            
            return Result.success("渠道对账文件上传成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("渠道对账文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 查询对账差异列表
     * @param reconciliationId 对账结果ID
     * @return 差异列表
     */
    @GetMapping("/diffs/{reconciliationId}")
    public Result<?> getReconciliationDiffs(@PathVariable Long reconciliationId) {
        try {
            // 此处简化实现，实际应根据对账结果ID查询差异列表
            Map<String, Object> params = new HashMap<>();
            params.put("reconciliationId", reconciliationId);
            // 调用查询逻辑
            return Result.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询对账差异列表失败：" + e.getMessage());
        }
    }
}